package com.github.base.mvp

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.MutableLiveData
import androidx.viewbinding.ViewBinding
import com.github.base.RegisterPresenter
import java.lang.IllegalArgumentException
import kotlin.reflect.KClass


/**
 * MVP 开发模式
 * @author <a href="https://github.com/karai-oss">Mr.xie</a>
 * @Date 2025/4/23
 */


/**
 * 视图顶级接口
 */
interface IView {

}


/**
 * 模型顶级接口
 */
interface IModel {

}

/**
 * Presenter顶级接口
 */

interface IPresenter {

}


/**
 * View基类接口
 */
interface IBaseView<VB : ViewBinding> : IView {


    /**
     * 获取 ViewBinding
     */
    fun startBinding(container: ViewGroup?, inflater: LayoutInflater?, savedInstanceState: Bundle?): VB


    /**
     * 初始化数据
     */
    fun initData();


    /**
     * 初始化视图
     */
    fun initView();


    /**
     * 在set UI 以后的视图函数
     */
    fun initBeforeView();

    /**
     * 一些事件监听
     */
    fun listener();


    /**
     * 用于去加载presenter
     */
    fun startPresenter();
}


/**
 * Activity 基类
 */
abstract class BaseBindingActivity<VB : ViewBinding> : AppCompatActivity(), IBaseView<VB> {

    public lateinit var binding: VB;

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = startBinding(null, null, savedInstanceState);
        initData();
        initView()
        listener();
        setContentView(binding.root)
        initBeforeView();
    }

}


/**
 * Fragment 基类
 */

abstract class BaseBindingFragment<VB : ViewBinding> : Fragment(), IBaseView<VB> {

    public lateinit var binding: VB;

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        binding = startBinding(container , inflater , savedInstanceState);
        initData();
        initView()
        listener();
        return binding.root
    }
}

object BaseFrame {
    val registerMap = MutableLiveData(mutableMapOf<String, IPresenter>())
}


/**
 * 注册Presenter
 */
fun Any.registerPresenter(vararg activitys: KClass<*>) {

    activitys.forEach {
        val registerPersenterAnno =
            it.annotations.filter {
                it.annotationClass.equals(RegisterPresenter::class)
            }

        if (registerPersenterAnno.size > 1) {
            throw IllegalArgumentException("RegisterPresenter 注解只能标注一个")
        }

        val annotation = registerPersenterAnno[0] as RegisterPresenter;
        for ((index, presenterClazz) in annotation.presenterClazz.withIndex()) {
            // 获取 KClass 的 Java 类型
            val javaClass = presenterClazz.java
            // 创建实例
            val objectInstance: Any? = try {
                javaClass.getDeclaredConstructor().newInstance()
            } catch (e: Exception) {
                Log.e("TAG", "registerPresenter: Failed to create instance for ${presenterClazz.simpleName}: ${e.message} ")
                null
            }

            // 获取类的简单名称
            val simpleName = it.simpleName;

            // 检查 BaseFrame.registerMap.value 是否为 null
            if (BaseFrame.registerMap.value != null && objectInstance != null) {
                BaseFrame.registerMap.value?.put(simpleName!!, objectInstance as IPresenter)
            }
        }
    }
}





/**
 * 扩展获取Presenter
 */
fun <P : IPresenter> Any.mapPresenter(clazz: KClass<*>): P {
    val presenter = BaseFrame.registerMap.value?.get(clazz.simpleName)

    return presenter as P;
}